package com.wondertek.mist.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.Environment;

public class ResourcesDowner {
	
	public static String downloadFile(final String downloadUrl,File saveDir) {
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(downloadUrl);
		InputStream is = null;
		String returnDownloadFileName = "";
		FileOutputStream fileOutputStream = null;
		File file = null;
		try {
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {				
				is = entity.getContent();
				if (is != null) {
					
					if (!saveDir.exists())saveDir.mkdirs();					
					file = new File(saveDir, getFileName(downloadUrl));					
					returnDownloadFileName = file.getPath();
					fileOutputStream = new FileOutputStream(file);
					byte[] buf = new byte[2048];
					int len = -1;					
					while ((len = is.read(buf)) != -1) {						
						fileOutputStream.write(buf, 0, len);						
					}
					fileOutputStream.flush();
				}
			}
		} catch (Exception e) { 
			returnDownloadFileName = "";
			if (file != null)
				file.delete();
		} finally {
			try {
				if (fileOutputStream != null)
					fileOutputStream.close();
				if (is != null)
					is.close();
				client.getConnectionManager().shutdown(); 
			} catch (IOException ex) {
			}
		}
		return returnDownloadFileName;
	}
	
	public static String getFileName(String url) {
		String fileName = "";
		if (!StringUtils.isBlank(url)) {
			int index = url.lastIndexOf('/');
			if (index > -1) {
				fileName = url.substring(index + 1);
			} else {
				fileName = url;
			}
		}
		return fileName;
	}

	
	
}
